package org.hadoop.dao;

import org.hadoop.entity.Student;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Repository//表明这是一个数据层
public class HiveDao {
    public List<Student> Students() throws SQLException {
        List<Student> students = new ArrayList<>();
        //连接对象
        Connection con = null;
        try {
            //加载驱动
            Class.forName("org.apache.hive.jdbc.HiveDriver");
            String url="jdbc:hive2://master:10000/bigdata2";
            //得到连接对象
            con= DriverManager.getConnection(url,"c","xx");//hive的user和password是空，任意填写
            //通过连接对象去生成语句对象
            Statement statement = con.createStatement();
            //通过语句对象执行sql获取结果集
            ResultSet resultSet = statement.executeQuery("select * from student");
            //遍历取值
            while (resultSet.next()){
                //得到四个属性
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String address = resultSet.getString("address");
                int age = resultSet.getInt("age");
                //赋值
                Student student = new Student();
                student.setId(id);
                student.setName(name);
                student.setAddress(address);
                student.setAge(age);
                //将对象放入list
                students.add(student);
                System.out.println(id+"-------- "+name+"-------- "+address+" --------"+age);
            }
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if(con!=null){
                con.close();
            }
        }
        return students;
    }
}
